import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/entity/tag_entity.dart';
import 'package:dailoz/entity/task_entity.dart';
import 'package:dailoz/enum/modify_task_enum.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/service/tag_service/tag_service.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/view_model/tag.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ModifyPageViewModel extends ChangeNotifier {
  String? _taskContent = "";
  DateTime? _date = DateTime.now();
  DateTime? _startTime = DateTime.now();
  DateTime? _endTime = DateTime.now();
  String? _groupValue = "";
  String? _description = "";
  String? _tag = "";
  int? _status;

  final List<String> _selectedTagList = [];
  final List<Tag> _tagsList = [];

  final Map<String, Widget> _showTagList = {};

  bool _isLoading = false;

  bool get isLoading {
    return _isLoading;
  }

  int? get status {
    return _status;
  }

  String? get groupValue {
    return _groupValue;
  }

  String? get description {
    return _description;
  }

  DateTime? get date {
    return _date;
  }

  DateTime? get startTime {
    return _startTime;
  }

  DateTime? get endTime {
    return _endTime;
  }

  String? get taskContent {
    return _taskContent;
  }

  void changeEndTime(DateTime newTime) {
    _endTime = newTime;
    notifyListeners();
  }

  void changeStartTime(DateTime newTime) {
    _startTime = newTime;
    notifyListeners();
  }

  void changeDate(DateTime newTime) {
    _date = newTime;
    notifyListeners();
  }

  void changeGroupValue(newValue) {
    _groupValue = newValue;
    notifyListeners();
  }

  void changeSelected(Tag tag) {
    tag.isSelected = !tag.isSelected!;
    if (tag.isSelected == true) {
      _selectedTagList.add(tag.tagId);
    } else {
      _selectedTagList.remove(tag.tagId);
    }
    notifyListeners();
  }

  void changeDeleted(Tag tag) {
    tag.isDeleted = !tag.isDeleted!;
    notifyListeners();
  }

  void deleteTag(Tag tag) async {
    try {
      var response = await HttpUtil().delete("/tag", {"tagId": tag.tagId});
      if (response['code'] == 200) {
        _showTagList.remove(tag.tagId);
        fetchTagList();
        notifyListeners();
        showToast("Success!");
      }
    } catch (e) {
      print(e);
    } finally {
      notifyListeners();
    }
  }

  Future<bool> addTag(String tagContent) async {
    final prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString('user-id');
    try {
      var response = await HttpUtil()
          .post("/user/userTag", {"userId": userId, "tagContent": tagContent});
      if (response['code'] == 200) {
        fetchTagList();
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<void> fetchTask(String? taskId) async {
    _isLoading = true;
    try {
      var response = await HttpUtil().get("/task/taskId", data: {"id": taskId});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.code == 200) {
        TaskEntity taskEntity = TaskEntity.fromJson(responseJsonEntity.data);
        _taskContent = taskEntity.taskContent;
        _date = DateTime.parse(taskEntity.startTime);
        _startTime = DateTime.parse(taskEntity.startTime);
        _endTime = DateTime.parse(taskEntity.endTime);
        _description = taskEntity.description;
        _groupValue = taskEntity.type;
        _tag = taskEntity.tag;
        _status = taskEntity.status;
      }
      _isLoading = false;
    } catch (e) {
      print(e);
    }
    _isLoading = false;
    notifyListeners();
  }

  Future<void> fetchTagList() async {
    _isLoading = true;
    List<dynamic> tagList = await TagService.getTagList();
    _isLoading = false;
    _tagsList.clear();
    _selectedTagList.clear();
    _showTagList.clear();
    for (var tag in tagList) {
      TagEntity tagEntity = TagEntity.fromJson(tag);
      _tagsList.add(Tag(false, tagEntity.id, tagEntity.tagContent, false));
    }
    List<String> list = _tag!.split(",");
    for (int index = 0; index < list.length; index++) {
      for (int j = 0; j < _tagsList.length; j++) {
        if (list[index] == _tagsList[j].tagName) {
          _tagsList[j].isSelected = true;
          _selectedTagList.add(_tagsList[j].tagId);
        }
      }
    }
    notifyListeners();
  }

  List<Widget> generateTag() {
    if (_tagsList.isNotEmpty) {
      for (Tag tag in _tagsList) {
        _showTagList[tag.tagId] = GestureDetector(
          onTap: () {
            changeSelected(tag);
          },
          child: Stack(
            children: [
              GestureDetector(
                onLongPress: () {
                  changeDeleted(tag);
                },
                child: Container(
                  width: SizeConfig.getProportionateScreenWidth(77.0),
                  height: SizeConfig.getProportionateScreenHeight(34.0),
                  decoration: BoxDecoration(
                    color: tag.isSelected == true
                        ? Colors.red
                        : const Color(0xffECEAFF),
                    borderRadius: BorderRadius.circular(22.0),
                  ),
                  child: Center(
                    child: Text(
                      tag.tagName!,
                      style: const TextStyle(
                        color: Colors.black,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
              ),
              tag.isDeleted == true
                  ? Positioned(
                      right: 0,
                      child: SizedBox(
                        width: 15.0,
                        height: 15.0,
                        child: GestureDetector(
                          onTap: () async {
                            deleteTag(tag);
                          },
                          // onTap: deleteFunction,
                          child: const CircleAvatar(
                            backgroundColor: Colors.red,
                            child: Icon(
                              Icons.remove,
                              size: 15.0,
                            ),
                          ),
                        ),
                      ),
                    )
                  : const Text(""),
            ],
          ),
        );
      }
    } else {
      _showTagList["empty"] = const Center(child: Text("快去添加你的标签吧!"));
    }
    return _showTagList.values.toList();
  }

  Future<ModifyTaskEnum> modifyTask(Map<String, dynamic> taskInfo) async {
    final prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("user-id");
    taskInfo['userId'] = userId;
    taskInfo['startTime'] = DateTime(_date!.year, _date!.month, _date!.day,
            _startTime!.hour, _startTime!.minute)
        .toString();
    taskInfo['endTime'] = DateTime(_date!.year, _date!.month, _date!.day,
            _endTime!.hour, _endTime!.minute)
        .toString();
    taskInfo['tagList'] = _selectedTagList;
    taskInfo['status'] = _status;
    taskInfo['type'] = _groupValue;
    if (taskInfo['taskContent'] == "") {
      return ModifyTaskEnum.taskContentNull;
    }
    if (taskInfo['tagList'].isEmpty) {
      return ModifyTaskEnum.tagNull;
    }
    try {
      Map<String, dynamic> response = await HttpUtil().put("/task", taskInfo);
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      switch (responseJsonEntity.code) {
        case 200:
          showToast(responseJsonEntity.message);
          return ModifyTaskEnum.modified;
        case 50004:
          showToast(response['message']);
          return ModifyTaskEnum.hasExist;
        default:
          showToast(responseJsonEntity.message);
          return ModifyTaskEnum.fail;
      }
    } catch (e) {
      print(e);
      return ModifyTaskEnum.fail;
    }
  }
}
